package com.bum.api.core.util.load;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;

public class BaseParser {
	public static final String[]	WAP_HEADERS		= {
		"User-Agent", "Mozilla/5.0 (Linux; U; Android 2.2; en-us; DROID2 GLOBAL Build/S273) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
		"Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
		"Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
		"Accept-Language", "en-us,en;q=0.5",
		"Host", "m.phim.clip.vn"
												};

	public static URLConnection getConnection(String hostName, String[] headers) throws Exception {
		URI uri = new URI(null, hostName, null);
		URL url = uri.normalize().toURL();
		URLConnection conn = url.openConnection();

		if (headers != null) {
			for (int i = 0, n = headers.length / 2; i < n; i++) {
				conn.setRequestProperty(headers[2 * i], headers[2 * i + 1]);
			}
		} else {
			for (int i = 0, n = WAP_HEADERS.length / 2; i < n; i++) {
				conn.setRequestProperty(WAP_HEADERS[2 * i], WAP_HEADERS[2 * i + 1]);
			}
		}
		return conn;
	}

	public static String loadHtml(String hostName, String[] headers) {
		String buffer = null;

		try {
			HttpURLConnection conn = (HttpURLConnection) getConnection(hostName, headers);
			buffer = getResponseContent(conn, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (buffer == null) {
			return null;
		}

		return buffer;
	}

	public static String loadHtmlByPost(String hostName, String query) {
		return loadHtmlByPost(hostName, query, null, null);
	}

	public static String loadHtmlByPost(String hostName, String query, String[] headers, Boolean followRedirects) {
		String buffer = null;
		OutputStream output = null;
		try {
			byte[] bOut = query.getBytes();

			if (ArrayUtils.isEmpty(headers)) {
				headers = WAP_HEADERS.clone();
			}

			headers = (String[]) ArrayUtils.addAll(headers, new String[] {
					"Content-Length", String.valueOf(bOut.length)
			});

			HttpURLConnection conn = (HttpURLConnection) getConnection(hostName, headers);
			if (followRedirects != null) {
				conn.setInstanceFollowRedirects(followRedirects);
			}

			conn.setRequestMethod("POST");
			conn.setDoOutput(true);

			output = conn.getOutputStream();

			output.write(bOut);
			output.flush();

			buffer = getResponseContent(conn, null);
		} catch (Exception e) {
			System.err.println(String.format("Time: %d\nUrl: %s\nMessage: %s", System.currentTimeMillis(), hostName, e.getMessage()));
			e.printStackTrace();
		} finally {
			if (output != null)
				try {
					output.close();
				} catch (IOException logOrIgnore) {
				}
		}

		if (buffer == null) {
			return null;
		}

		String html = StringEscapeUtils.unescapeHtml(buffer).replace(" ", " ").replaceAll("\\s+", " ");
		html = VietKeyDecoder.decode(html);
		return html;
	}

	public static String getResponseContent(HttpURLConnection conn, String charset) {
		StringBuffer buffer = new StringBuffer();
		try {
			InputStream inStream = null;
			try {
				inStream = conn.getInputStream();
			} catch (IOException e) {
				if (conn.getResponseCode() == 500) {
					inStream = conn.getErrorStream();
				}
			}

			if (null == inStream) {
				return null;
			}

			String contentEncoding = conn.getContentEncoding();
			if (StringUtils.isNotBlank(contentEncoding) && contentEncoding.indexOf("gzip") != -1) {
				inStream = new GZIPInputStream(inStream);
			}

			charset = StringUtils.isBlank(charset) ? "UTF-8" : charset;
			BufferedReader in = new BufferedReader(new InputStreamReader(inStream, charset));

			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				buffer.append(inputLine + " ");
			}
			in.close();
		} catch (Exception e) {
			System.err.println(String.format("Time: %d\nUrl: %s\nMessage: %s", System.currentTimeMillis(), conn.getURL().toString(), e.getMessage()));
			e.printStackTrace();
		}

		return buffer.toString();
	}
	
	public static String parseContent(String responseContent, String tokenStart, String tokenEnd) {
		if (StringUtils.isBlank(responseContent)) {
			return null;
		}

		String tableContent = null;

		int posStart = 0;
		if (tokenStart != null) {
			posStart = responseContent.indexOf(tokenStart);

			if (posStart < 0) {
				return null;
			}
			posStart += tokenStart.length();
		}

		int posEnd = -1;
		if (tokenEnd != null) {
			posEnd = responseContent.indexOf(tokenEnd, posStart);
		}

		if (posEnd > posStart) {
			tableContent = responseContent.substring(posStart, posEnd);
		} else if (posEnd == posStart) {
			return "";
		} else {
			tableContent = responseContent.substring(posStart);
		}

		return tableContent;
	}
}
